<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false" title="AI预测">
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-form-item
        label="训练模板"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
      >
        <a-select
          show-search
          placeholder="请选择训练模板"
          v-model="model.templateIds"
          v-decorator="['name', { rules: [{ required: true, message: '请选择训练模板' }] }]"
          @change="changeMode"
          allowClear
        >
          <a-select-option v-for="item in modelTemplateList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="槽号"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        :required="false"
      >
        <j-select-data-slot
          placeholder="请选择槽号"
          :multi="true"
          :buttons="false"
          v-model="model.slotIds"
        ></j-select-data-slot>
      </a-form-item>
      <a-form-item
        label="预测序列长度"
        :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        prop="predictNumber"
      >
        <a-input-number :style="{ width: 'calc(50% - 60px)' }" value="1" v-model="model.predictNumber" />
      </a-form-item>
      <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button htmlType="submit" type="primary" :loading="confirmLoading" @click="handleSubmit">预测</a-button>
        <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
      </a-form-item>
    </a-form-model>
    <j-modal width="80%" :visible="resultVisible" title="预测结果" :draggable="true" @cancel="resultCancel">
      <template>
        <a-table
          ref="table"
          size="middle"
          :scroll="{ x: true }"
          bordered
          :columns="columns"
          :dataSource="resultList"
          :pagination="false"
          class="j-table-force-nowrap"
        >
          <template slot="resultSlot" slot-scope="text">
            <a-tag v-for="tag in text" :key="tag" :color="'geekblue'">
              {{ tag.toUpperCase() }}
            </a-tag>
          </template>
          <!-- <template slot="modelIdSlot" slot-scope="text">
            {{ getModelName(text) }}
          </template>
          <span slot="resultSlot" slot-scope="text">
            <a-tag
              v-for="tag in text"
              :key="tag"
              :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
            >
              {{ tag.toUpperCase() }}
            </a-tag>
          </span> -->
        </a-table>
      </template>
      <template slot="footer">
        <a-button @click="showTb()">图表查看</a-button>
        <a-button @click="resultCancel">关闭</a-button>
      </template>
    </j-modal>

    <j-modal width="80%" :visible="chartVisible" :title="selectTemplateName" @cancel="onCancel" :draggable="true">
      <template>
        <!-- <line-chart-multid
          :key="new Date().getTime()"
          :dataSource="lineData"
          :fields="model.slotIds"
          :height="height"
        /> -->
        <div id="main" :style="{ width: '100%', height: height + 'px' }"></div>
      </template>
      <template slot="footer">
        <a-button @click="onCancel">关闭</a-button>
      </template>
    </j-modal>
  </a-card>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-liquidfill'
import { getAction, postAction } from '@/api/manage'
import JSelectDataSlot from '@/components/jeecgbiz/JSelectDataSlot2'
import LineChartMultid from '@/components/chart/LineChartMultid'
const colorList = [
  'blue',
  '#ff4683',
  '#F5222D',
  '#FA541C',
  '#FAAD14',
  '#13C2C2',
  '#52C41A',
  '#1890FF',
  '#2F54EB',
  '#722ED1',
  '#2f4f4f',
]
export default {
  name: 'PredictPlus',
  components: {
    JSelectDataSlot,
    LineChartMultid,
  },
  data() {
    return {
      confirmLoading: false,
      modelTemplateList: [],
      model: {
        templateIds: '',
        slotIds: '',
        predictNumber: '',
      },
      selectTemplateName: '',
      validatorRules: {
        predictNumber: [{ required: true, message: '请填写预测的天数!' }],
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },

        {
          title: '模型',
          dataIndex: 'model_name',
          align: 'center',
          width: 140,
        },
        {
          title: '槽号',
          dataIndex: 'slot_id',
          align: 'center',
          width: 140,
        },
        {
          title: '预测结果',
          dataIndex: 'result',
          align: 'center',
          width: 260,
          scopedSlots: { customRender: 'resultSlot' },
        },
        {
          title: '状态',
          dataIndex: 'message',
          align: 'center',
          width: 100,
        },
      ],
      confirmLoading: false,
      resultVisible: false,
      chartVisible: false,
      resultList: [],
      lineData: [],
      fields: [],
      height: 500,
      myChart: null,
    }
  },
  created() {
    this.loadModelTemplate()
  },
  methods: {
    changeMode(value) {
      let obj = this.modelTemplateList.find((i) => {
        return i.id === value
      })
      this.selectTemplateName = obj.name
    },
    loadModelTemplate() {
      getAction('/modelBase/template/list', { pageSize: 9999 })
        .then((res) => {
          if (res.success) {
            var dataSource = res.result.records
            for (let i = 0; i < dataSource.length; i++) {
              this.modelTemplateList.push({ id: dataSource[i].id, name: dataSource[i].name })
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    searchReset() {
      this.model.dataSoltIds = ''
      this.model.templateIds = ''
      this.model.predictNumber = ''
    },

    // handler
    handleSubmit() {
      let that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          var param = {}
          param['templateIds'] = []
          param['predictNumber'] = that.model.predictNumber
          param['slotIds'] = that.model.slotIds
          param['templateIds'].push(that.model.templateIds)
          this.confirmLoading = true
          postAction('/modelBase/model/predictPlus', param).then((res) => {
            that.confirmLoading = false
            if (res.success) {
              that.resultVisible = true
              that.resultList = res.result
              //that.showTb()
            } else {
              that.$message.error(res.message)
            }
            that.confirmLoading = false
          })
        }
      })
    },
    showTb() {
      var that = this
      that.lineData = []
      //{ "type": "2024-09-01 00:00:00", "2231 ": 3940, "2232 ": 3950 }
      for (let i = 0; i < that.resultList[0].result.length; i++) {
        var lineObj = that.lineData.find((o) => o.type == '序列' + i)
        if (!lineObj) {
          var obj = { type: '序列' + i }
          for (let i = 0; i < that.model.slotIds.length; i++) {
            const soltId = that.model.slotIds[i]
            obj[soltId] = that.getValue(soltId, i)
          }
          that.lineData.push(obj)
        }
      }
      // that.resultList.forEach((e) => {
      //   debugger
      //   var lineObj = that.lineData.find((o) => o.type == e.date)
      //   if (!lineObj) {
      //     var obj = { type: e.date }
      //     for (let i = 0; i < that.queryParam.dataSoltIds.length; i++) {
      //       const soltId = that.queryParam.dataSoltIds[i]
      //       obj[soltId] = that.getValue(soltId, e.date)
      //     }
      //     that.lineData.push(obj)
      //   }
      // })
      that.chartVisible = true
      setTimeout(() => {
        if (that.myChart) {
          that.myChart.clear()
        }
        that.loadTb()
      }, 1000)
    },
    getValue(soltId, index) {
      var that = this
      var obj = that.resultList.find((item) => item.slot_id == soltId)
      if (obj) {
        return parseFloat(obj.result[index])
      }
      return 0
    },
    loadTb() {
      var that = this
      var allValues = []
      that.resultList.forEach((element) => {
        allValues = allValues.concat(element.result)
      })
      console.log('allValues,' + allValues)
      var yAxisMin = parseFloat(Math.min.apply(null, allValues) - 0.1).toFixed(2)
      var yAxisMax = parseFloat(Math.max.apply(null, allValues) + 0.05).toFixed(2)

      var _series = [
        {
          name: '电压',
          type: 'line',
          showSymbol: false,
          itemStyle: {
            color: 'blue',
          },
          data: [1, 2, 3, 4, 5],
        },
      ]
      _series = []

      for (let i = 0; i < that.resultList.length; i++) {
        var lineObj = {
          name: that.resultList[i]['slot_id'],
          type: 'line',
          showSymbol: false,
          itemStyle: {
            color: colorList[Math.random() * 10],
          },
          data: that.resultList[i].result,
        }
        _series.push(lineObj)
      }

      var dateList = []
      for (let i = 0; i < that.resultList[0].result.length; i++) {
        dateList.push('序列' + i)
      }

      that.loadXLTb2('main', '图表', _series, that.model.slotIds, yAxisMin, yAxisMax, '日期', '值', dateList)
    },
    loadXLTb2(divId, title, _series, legendData, yAxisMin, yAxisMax, xAxisName, yAxisName, dateList) {
      var that = this
      var chartDom = document.getElementById(divId)
      var myChart = echarts.init(chartDom)
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          position: function (pt) {
            return [pt[0], '10%']
          },
        },
        title: {
          // left: 'center',
          text: '', // '[ ' + that.modelBase.code + ' ] '+title,
        },
        legend: {
          data: legendData,
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {},
          },
        },
        grid: { containLabel: true },
        xAxis: {
          name: xAxisName,
          type: 'category',
          boundaryGap: false,
          data: dateList,
          // axisLabel: {
          //     interval: 30, // 显示所有刻度
          //     rotate: 30 // 将刻度旋转30度
          // }
        },
        yAxis: {
          name: yAxisName,
          type: 'value',
          // boundaryGap: [0, '100%'],
          // interval: that.yAxisInterval, //分割刻度
          min: yAxisMin,
          max: yAxisMax,
        },
        // dataZoom: [
        //   {
        //     type: 'inside',
        //     start: 0,
        //     end: 100,
        //   },
        //   {
        //     start: 0,
        //     end: 100,
        //   },
        // ],
        series: _series,
      }
      option && myChart.setOption(option)
      window.onresize = function () {
        setTimeout(function () {
          myChart.resize()
        }, 10)
      }
    },

    resultCancel() {
      this.resultVisible = false
    },
    onCancel() {
      this.chartVisible = false
    },
  },
}
</script>